package service

import (
	"errors"
	"go-ecommerce/internal/model"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
)

// GetAdminByID 根据 ID 获取管理员信息
func GetAdminByID(db *gorm.DB, id uint) (*model.Admin, error) {
	var admin model.Admin
	if err := db.First(&admin, id).Error; err != nil {
		return nil, err
	}
	return &admin, nil
}

// CreateAdmin 添加管理员
func CreateAdmin(db *gorm.DB, username, password string) error {
	// 判断是否存在
	var count int64
	db.Model(&model.Admin{}).Where("username = ?", username).Count(&count)
	if count > 0 {
		return errors.New("管理员已存在")
	}

	// 密码加密
	hashedPwd, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		return errors.New("密码加密失败")
	}

	// 创建记录
	admin := model.Admin{
		Username: username,
		Password: string(hashedPwd),
	}
	return db.Create(&admin).Error
}

// GetAdminList 获取管理员列表
func GetAdminList(db *gorm.DB) ([]model.Admin, error) {
	var list []model.Admin
	err := db.Select("id", "username", "created_at").Find(&list).Error
	return list, err
}

// UpdateAdmin 修改管理员用户名
func UpdateAdmin(db *gorm.DB, id uint, username string) error {
	return db.Model(&model.Admin{}).Where("id = ?", id).Update("username", username).Error
}

// DeleteAdmin 删除管理员（软删）
func DeleteAdmin(db *gorm.DB, id uint) error {
	return db.Delete(&model.Admin{}, id).Error
}

// GetAdminPermissionIDs 获取管理员的所有权限ID
func GetAdminPermissionIDs(db *gorm.DB, adminID uint) ([]uint64, error) {
	var roleIDs []uint64
	if err := db.Table("admin_role").Where("admin_id = ?", adminID).Pluck("role_id", &roleIDs).Error; err != nil {
		return nil, err
	}
	if len(roleIDs) == 0 {
		return []uint64{}, nil
	}

	var permissionIDs []uint64
	if err := db.Table("role_permission").Where("role_id IN ?", roleIDs).Pluck("permission_id", &permissionIDs).Error; err != nil {
		return nil, err
	}
	return permissionIDs, nil
}
